package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.commom.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author by jojo
 * @Date 2022/3/7
 * @Description
 */
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        //校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数不能为null");
        }
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)) {
            //手机号和密码登录
            //使用该手机号查询ApUser数据库
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            //校验该手机号是否正确
            if (apUser == null) {
                log.error("手机号不正确");
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号不正确！！！");
            }
            String salt = apUser.getSalt();
            //密码加盐md5加密
            String loginPwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //判断密码是否正确
            if (!apUser.getPassword().equals(loginPwd)) {
                log.error("密码错误。。。");
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            Map map = new HashMap<>();
            //将密码和盐设置为空,封装返回
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("token", token);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //判断设备id是否为空
            if (dto.getEquipmentId() == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "设备id为空");
            }
            //直接颁发token
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
